﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HCQ2_Common;
using HCQ2_IDAL;

namespace HCQ2_BLL.Order
{
    /// <summary>
    /// 创建订单号
    /// </summary>
    /// <remarks>
    /// 订单号生成规则："0"+产品类别编码+年月日+五位流水号（从10000开始），例如：012019082810001；
    /// 如果订单有多个商品，则以上订单号作为父订单号，末尾增加从01开始的2位流水作为订单号，例如：01201908281000101；如果订单只有一个商品，则订单号和父订单号都按以上规则生成
    /// </remarks>
    public class OrderCreate
    {
        private static object obj = new object();

        /// <summary>
        /// 数据库操作
        /// </summary>
        public IDBSession DBSession { get; set; }

        /// <summary>
        /// 版本，ZS或CS类别
        /// </summary>
        public string VersionType { get; set; }

        /// <summary>
        /// 前缀
        /// </summary>
        public string Prefix { get; set; }

        /// <summary>
        /// 流水号，通过数据库表N_OrderNumber自动ID获取
        /// </summary>
        public int OrderNum { get; set; }


        public string TimeFormat { get; set; }
        /// <summary>
        /// 创建一个对象创建订单号
        /// </summary>
        /// <param name="dBSession"></param>
        /// <param name="typeCode"></param>
        /// <param name="prefix"></param>        
        public OrderCreate(IDBSession dBSession,string prefix="VR",bool timeFormat=true)
        {
            this.VersionType = ConfigurationHelper.AppSetting("VersionType");            
            this.DBSession = dBSession;
            this.Prefix = prefix;
            GetOrderNum();

            if (timeFormat)
            {
                TimeFormat = "yyyyMMdd";
            }
            else {
                TimeFormat = "yyyyMMddHHmmssfff";
            }
        }

        /// <summary>
        /// 创建一个订单号
        /// </summary>
        /// <returns></returns>
        public string NewOrderCode()
        {
            lock (obj) {
                string time = DateTime.Now.ToString(TimeFormat);
                /// 2021-11-10：老谭要求把prefix的VR前缀取消，所以取消这个，前缀直接在VersionType参数里面配置
                //return $"{VersionType}{Prefix}{time}{OrderNum}";
                return $"{VersionType}{time}{OrderNum}";
            }
        }

        /// <summary>
        /// 获取当前流水号
        /// </summary>
        private void GetOrderNum()
        {
            lock (obj)
            {
                this.OrderNum = DBSession.IN_OrderNumberDAL.GetMaxOrderNumber();
            }
        }
    }
}
